import { Component, OnInit, ViewChild, ElementRef, Input } from '@angular/core';
import { MysqlService, DBConfig } from 'src/app/service/mysql.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzTreeNode, NzTreeNodeOptions, NzMessageService, NzNotificationService, NzTreeComponent } from 'ng-zorro-antd';
import { debounceTime } from 'rxjs/operators';
import { Subject } from 'rxjs';


@Component({
  selector: 'app-dbmanager',
  templateUrl: './dbmanager.component.html',
  styleUrls: ['./dbmanager.component.css']
})
export class DbmanagerComponent implements OnInit {

  drawerVisible:boolean = false;
  validateForm:FormGroup;
  singleControllerForm:FormGroup;
  treeData:any[] = [];
  dbConfig:DBConfig;

  selectedNode:NzTreeNode;
  expandNode:NzTreeNode;

  searchValue:string;
  delayedSearchValue:string;

  hideUnMatched:boolean = true;// 搜索时隐藏不匹配的项

  fields = [];// 选中表的字段列表

  @ViewChild('tree',{static:false})
  tree:NzTreeComponent;

  searchInput$ = new Subject();
  angularModel:string = "";

  popOverVisible_createMybatisSaveOne:boolean = false;
  packagePath_createMybatisSaveOne:string = 'com.ccsoft.femis.model.ContactType';

  popOverVisible_createSpringDao:boolean = false;
  modelName_createSpringDao:string = 'SimpleBasedata';

  popOverVisible_createSpringController:boolean = false;
  modelName_createSpringController:string = 'SimpleBasedata';

  upperAttribute:boolean = false;

  visible_SingleControllerForm:boolean = false;

  constructor(
    private mysqlService:MysqlService,
    private fb:FormBuilder,
    private noti:NzNotificationService
  ) { }

  ngOnInit() {
    // 初始化表单
    this.validateForm = this.fb.group({
      server:['49.234.149.119',Validators.required],
      port:['3306',Validators.required],
      userName:['root',Validators.required],
      password:['!Xdf123456',Validators.required]
    });

    // 单表控制器代码
    this.singleControllerForm = this.fb.group({
      tableName:[null,Validators.required],
      modelName:[null,Validators.required],
      detailService:[null,Validators.required]
    });

    this.searchInput$.pipe(debounceTime(700)).subscribe(
      (val:string)=>this.delayedSearchValue = val
    )

  }

  connectServer(){
    this.drawerVisible = !this.drawerVisible;
  }

  closeDrawer(e){
    this.drawerVisible = false;
  }

  connectDB(){
    this.dbConfig = this.getDbConfig();// 将抽屉中的表单数据转换为对象
    this.drawerVisible = false;// 关闭抽屉

    this.mysqlService.buildFieldTree(this.dbConfig).subscribe(
      ( res:any[] )=>{
        console.log(res);
        this.treeData = res;
      },error=>this.msg('构建树时出错！')
    )

  }

  getDbConfig():DBConfig{
    let config = new DBConfig();
    config = new DBConfig();
    config.server = this.validateForm.value["server"];
    config.port = this.validateForm.value["port"];
    config.dbName = "mysql";
    config.dbUserName = this.validateForm.value["userName"];
    config.dbUserPwd = this.validateForm.value["password"];

    return config;
  }

  buildTree(nodes:any[]){
    if( nodes.length<=0 ) return;
    nodes.forEach(ele => {
      let node = {'title':ele.SCHEMA_NAME,'key':ele.SCHEMA_NAME};
      console.log(ele.SCHEMA_NAME + '-' + ele.DEFAULT_CHARACTER_SET_NAME);
      
      // this.treeData.push(node);
      this.treeData = this.treeData.concat(node);
    });
  }

  submitForm(){
    this.connectDB();
  }

  getTables(dbName:string){
    if(this.dbConfig === null){
      this.noti.blank('通知','还没有链接数据库！');
      return;
    }

    if(this.selectedNode === null){
      this.noti.blank('通知','没有选中节点！');
      return;
    }

    this.mysqlService.getTables(this.dbConfig,dbName).subscribe(
      ( res:any[] )=>{
        console.log(res);

        // 构建表名构成的数组
        let nodes = [];
        res.forEach(ele => {
          nodes.push({'title':ele.table_name + ',' + ele.table_comment,'key':ele.table_name});
        });

        // 将表名数组拼接到树形结构中的指定数据库名下

      },error=>this.msg('获取所有表时出错！')
    )
  }

  msg(content:string){
    this.noti.blank('通知',content);
  }

  treeClick(e){
    this.selectedNode = e.node;
  }

  treeNodeExpand(e){
    this.expandNode = e.node;
    this.getTables(this.expandNode.key);
  }

  searchValueChange(e){

  }

  searchChange(e){
    this.searchInput$.next(e);
  }

  createAngularModel(){
    let node = this.tree.getSelectedNodeList()[0];
    let origin = this.tree.getSelectedNodeList()[0].origin.origin;
    
    if( !this.mysqlService.isTable(origin) ){
      this.msg('选中节点不是表！');
      return;
    }

    this.angularModel = this.mysqlService.createAngularModel(node.key);
    
  }


  clickSwitcher(){
    this.msg(this.hideUnMatched + '');
  }

  close(){
    this.drawerVisible = false;
  }


  // 生成 Mybatis 批量插入的 SQL 语句
  createMybatisSaveBatch(upperAttribute:boolean){
    let node = this.tree.getSelectedNodeList()[0];
    let origin = this.tree.getSelectedNodeList()[0].origin.origin;
    
    if( !this.mysqlService.isTable(origin) ){
      this.msg('选中节点不是表！');
      return;
    }

    this.angularModel = this.mysqlService.createMybatisSaveBatch(node.key,!upperAttribute);
  }


  // 生成 Mybatis 单行数据的新增/修改 SQL 语句
  // 触发服务中的具体实现的方法：save_packagePath_createMybatisSaveOne
  createMybatisSaveOne(){
    this.popOverVisible_createMybatisSaveOne = true;
  }

  // 创建 Mybatis - selectAll 方法
  createMybatisSelectAll(){
    let node = this.tree.getSelectedNodeList()[0];
    let origin = this.tree.getSelectedNodeList()[0].origin.origin;
    
    if( !this.mysqlService.isTable(origin) ){
      this.msg('选中节点不是表！');
      return;
    }

    this.angularModel = this.mysqlService.createMybatisSelectAll(node.key);
  }

  save_packagePath_createMybatisSaveOne(){
    if( this.packagePath_createMybatisSaveOne.length<=0 ){
      this.msg('包名必须设置！');
      return
    }

    this.popOverVisible_createMybatisSaveOne = false;

    let node = this.tree.getSelectedNodeList()[0];
    let origin = this.tree.getSelectedNodeList()[0].origin.origin;
    
    if( !this.mysqlService.isTable(origin) ){
      this.msg('选中节点不是表！');
      return;
    }

    console.log('开始调用服务层方法：upperAttribute=' + this.upperAttribute);
    this.angularModel = this.mysqlService.createMybatisSaveOne(node.key,
      this.packagePath_createMybatisSaveOne,this.upperAttribute);

  }


  // 生成 Spring DAO 自定义的三剑客：selectAll、saveOne、saveBatch
  createSpringDao(){
    this.popOverVisible_createSpringDao = true;
  }

  createSpringDaoGo(){
    let node = this.tree.getSelectedNodeList()[0];
    let origin = this.tree.getSelectedNodeList()[0].origin.origin;
    
    if( !this.mysqlService.isTable(origin) ){
      this.msg('选中节点不是表！');
      return;
    }

    this.angularModel = this.mysqlService.createSpringDao(node.key,this.modelName_createSpringDao);
  }

  createSpringController(){
    this.popOverVisible_createSpringController = true;
  }

  createSpringControllerGo(){
    let node = this.tree.getSelectedNodeList()[0];
    let origin = this.tree.getSelectedNodeList()[0].origin.origin;
    
    if( !this.mysqlService.isTable(origin) ){
      this.msg('选中节点不是表！');
      return;
    }

    this.angularModel = this.mysqlService.createSpringController(node.key,this.modelName_createSpringController);
  }

  createAngularService(){
    let node = this.tree.getSelectedNodeList()[0];
    let origin = this.tree.getSelectedNodeList()[0].origin.origin;
    
    if( !this.mysqlService.isTable(origin) ){
      this.msg('选中节点不是表！');
      return;
    }

    this.angularModel = this.mysqlService.createAngularService(node.key);
  }


  change_createMybatisSaveOne(e){
    console.log(e);
  }


  // 从远端服务器中获取数据更新本地数据
  refreshLocalData(){
    if( this.dbConfig === undefined || this.dbConfig === null ){
      this.msg('还没有设置连接服务器的参数！');
      return
    }
    

    this.mysqlService.buildFieldTree(this.dbConfig).subscribe(
      ( res:any[] )=>{
        console.log(res);
        this.treeData = res;
        this.msg('更新完毕！');
      },error=>this.msg('构建树时出错！')
    )

    this.drawerVisible = false;// 关闭抽屉

  } 


  createFieldString(){
    let node = this.tree.getSelectedNodeList()[0];
    let origin = this.tree.getSelectedNodeList()[0].origin.origin;
    
    if( !this.mysqlService.isTable(origin) ){
      this.msg('选中节点不是表！');
      return;
    }

    this.angularModel = this.mysqlService.createFieldString(node.key);
  }


  printEval(){
    let raw:string = '(meter + way) * cy';
    let data = {iid:1,meter:10,way:2,cy:3};
    let arr:{label:string,value:number}[] = [];
    let ret:string = raw;
    for(let attri in data){
      ret = ret.replace(attri,data[attri]);
    }

    console.log('替换后返回值是：' + ret);
    console.log(eval(ret));

  }

  // 生成代码模板代码
  createSingleTemplate(){
    this.angularModel = this.mysqlService.createSingleTemplate()
  }

  createSingleController(){
    console.log(this.singleControllerForm.value);
    let tableName:string = this.singleControllerForm.value.tableName;
    let modelName:string = this.singleControllerForm.value.modelName;
    let detailService = this.singleControllerForm.value.detailService;

    console.log('模式类名是：' + modelName + ',服务类名：' + detailService);
    this.angularModel = this.mysqlService.createSingleController(tableName,modelName,detailService);
  }


  // 保存抽屉组件中的表单 - 生成单表类型的控制器
  saveDrawer_SingleControllerParam(){
    this.createSingleController();
    this.visible_SingleControllerForm = false;
  }


  // 关闭抽屉组件
  cancelDrawerEdit(){
    this.visible_SingleControllerForm = false;
  }

}
